#pragma once


#include <iostream>
#include <pthread.h>
#include <queue>

#include "LockGuard.hpp"



const int defaultsize = 6;
template <class T>
class BlockQueue
{
public:
    BlockQueue(int cap = defaultsize)
    :_capacity(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
    }
    bool isFull()
    {
        return _q.size() == _capacity;
    }

    bool isEmpty()
    {
        return _q.size() == 0;
    }

    void Push(const T& in)
    {
        {
        LockGuard lock(&_mutex);
        // pthread_mutex_lock(&_mutex);
        while(isFull())
        {
            pthread_cond_wait(&_p_cond,&_mutex);
        }

        _q.push(in);

        pthread_cond_signal(&_c_cond);
        // pthread_mutex_unlock(&_mutex);
        }
    }

    void Pop(T*out)
    {
        {
        LockGuard lock(&_mutex);
        // pthread_mutex_lock(&_mutex);
        while(isEmpty())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }

        *out = _q.front();
        _q.pop();

        pthread_cond_signal(&_p_cond);
        // pthread_mutex_unlock(&_mutex);
        }
    }
    ~BlockQueue()
    {}
private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;
};